﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.BIM;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.HCLoad
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class cmdStartHCLoad : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			string message;
			if (!HCLoadUtility.IsInatallHCLoad70(out message))
			{
				YJKMessageBox.Show(message);
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			UIApplication application = cmdData.Application;
			Document document = application.ActiveUIDocument.Document;
			Selection selection = application.ActiveUIDocument.Selection;
			Transaction transaction = new Transaction(document, "负荷计算");
			string fileName = "";
			bool flag = false;
			transaction.Start();
			try
			{
				Product.Init();
				string workingLocation = Product.WorkingLocation;
				fileName = Path.Combine(workingLocation, document.Title + ".xml");
				EnergyDataSettings.GetFromDocument(document).ExportCategory = new ElementId(-2003600);
				if (!document.EnergyAnalysis())
				{
					TaskDialog.Show("盈建科提示", "没有可以计算的空间");
					transaction.Commit();
					return Autodesk.Revit.UI.Result.Cancelled;
				}
				GBXMLExportOptions gbxmlexportOptions = new GBXMLExportOptions();
				document.Export(workingLocation, document.Title + ".xml", gbxmlexportOptions);
				IList<HYSpaceInfo> allHYSpaceInfo = SpaceParameterOperate.GetAllHYSpaceInfo(document);
				IList<Element> elementByCategory = YJKElementFilter.GetElementByCategory(document, BuiltInCategory.OST_HVAC_Zones);
				if (allHYSpaceInfo != null)
				{
					SpaceParameterOperate.ModifyGBXml(workingLocation + "\\" + document.Title + ".xml", allHYSpaceInfo, elementByCategory);
				}
				transaction.Commit();
				flag = true;
			}
			catch (Exception ex)
			{
				string message2 = ex.Message;
				TaskDialog.Show("盈建科提示", message2);
				transaction.RollBack();
			}
			if (flag)
			{
				Process process = HCLoadUtility.GetHCloadProcess();
				if (process == null)
				{
					process = HCLoadUtility.StartHCLoad(fileName);
				}
				else
				{
					HCLoadUtility.SendMessageToReadGbxml(process, fileName);
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
